import request from "@/axios/request";

const {ElMessage} = require("element-plus");

export default {
    name: "TenantInfo",
    data() {
        // 手机号验证
        const checkPhone = (rule, value, callback) => {
            const phoneReg = /^1[3|4|5|6|7|8][0-9]{9}$/;
            if (!value) {
                return callback(new Error("电话号码不能为空"));
            }
            setTimeout(() => {
                if (!Number.isInteger(+value)) {
                    callback(new Error("请输入数字值"));
                } else {
                    if (phoneReg.test(value)) {
                        callback();
                    } else {
                        callback(new Error("电话号码格式不正确"));
                    }
                }
            }, 100);
        };
        // 邮箱验证
        const checkEmail = (rule, value, callback) => {
            const emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
            if (!value) {
                return callback(new Error("邮箱不能为空"));
            }
            setTimeout(() => {
                if (emailReg.test(value)) {
                    callback();
                } else {
                    callback(new Error("邮箱格式不正确"));
                }
            }, 100);
        };
        const checkPass = (rule, value, callback) => {
            if (!this.editJudge) {
                if (value == "") {
                    callback(new Error("请再次输入密码"));
                } else if (value !== this.form.password) {
                    callback(new Error("两次输入密码不一致!"));
                } else {
                    callback();
                }
            } else {
                callback();
            }
        };
        return {
            showpassword: true,
            judgeAddOrEdit: true,
            loading: true,
            editJudge: true,
            disabled: false,
            judge: false,
            dialogVisible: false,
            search: "",
            former_search: "",
            currentPage: 1,
            pageSize: 10,
            total: 0,
            allData: [],       // 存储全量数据
            tableData: [],     // 当前页数据
            form: {
                tenantId: null,
                username: "",
                password: "",
                phone: "",
                email: "",
            },
            rules: {
                username: [
                    {required: true, message: "请输入用户名", trigger: "blur"},
                ],
                password: [
                    {required: true, message: "请输入密码", trigger: "blur"},
                    {
                        min: 6,
                        max: 32,
                        message: "长度在 6 到 16 个字符",
                        trigger: "blur",
                    },
                ],
                phone: [{required: true, message: "请输入电话号码", validator: checkPhone, trigger: "blur"}],
                email: [{type: "email", message: "请输入邮箱地址", validator: checkEmail, trigger: "blur"}],
                checkPass: [{validator: checkPass, trigger: "blur"}],
            },
            editDisplay: {
                display: "block",
            },
            display: {
                display: "none",
            },
        };
    },
    computed: {
        paginatedData() {
            const start = (this.currentPage - 1) * this.pageSize;
            const end = start + this.pageSize;
            return this.allData.slice(start, end);
        }
    },
    created() {
        this.load();
        this.loading = true;
        setTimeout(() => {
            this.loading = false;
        }, 1000);
    },
    methods: {
        async load() {
            try{
                const res = await request.get("/tenant/findAll");
                if (res.code === 200) {
                    this.allData = res.data || [];
                    this.total = this.allData.length;
                    this.tableData = this.paginatedData;
                } else {
                    ElMessage.error(res.msg || "加载失败");
                    this.allData = [];
                    this.tableData = [];
                    this.total = 0;
                }
                this.loading = false;
            } catch (err){
                console.error(err);
                ElMessage.error("网络错误，请稍后再试");
                this.allData = [];
                this.tableData = [];
                this.total = 0; 
                this.loading = false;
            }
        },
        async filterData() {
            const res = await request.get("/tenant/findAll");
            if (res.code === 200) {
                this.allData = res.data || [];
                this.total = this.allData.length;
                this.tableData = this.paginatedData;
            } 
            
            let data = this.allData;
            if (this.search) {
                const id = parseInt(this.search);
                data = data.filter(item => item.tenantId === id);
            } else {
                this.load();
            }
            this.allData = data;
            this.total = data.length;
            this.tableData = this.paginatedData;
        },
        reset() {
            this.search = "";
            this.currentPage = 1;
            this.load();
        },
        
        add() {
            this.dialogVisible = true;
            this.$refs.form.resetFields();
            this.judgeAddOrEdit = false;
            this.editDisplay = {display: "none"};
            this.disabled = false;
            this.form = {
                tenantId: null,
                username: "",
                password: "",
                phone: "",
                email: "",
            };
            this.judge = false;
        },
        save() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    if (this.judgeAddOrEdit === false) {
                        //新增
                        const { username, password, phone, email } = this.form;
                        request.post("/tenant/register", { username, password, phone, email }).then((res) => {
                            if (res.code === 200) {
                                ElMessage.success("新增成功");
                                this.dialogVisible = false;
                                this.load(); 
                            } else {
                                ElMessage.error(res.msg || "新增失败");
                            }
                        });
                    } else {
                        //修改
                        request.put("/tenant/updateById", this.form).then((res) => {
                            if (res.code === 200) {
                                ElMessage.success("修改成功");
                                this.dialogVisible = false;
                                this.load(); // 重新加载全量数据
                            } else {
                                ElMessage.error(res.msg || "修改失败");
                            }
                        });
                    }
                }
            });
        },
        cancel() {
            this.$refs.form.resetFields();
            this.display = {display: "none"};
            this.editJudge = true;
            this.disabled = true;
            this.showpassword = true;
            this.dialogVisible = false;
        },
        handleEdit(row) {
            this.dialogVisible = true;
            // this.$refs.form.resetFields();
            this.form = {
                tenantId: row.tenantId || null,
                username: row.username || '',
                password: row.password || '',
                phone: row.phone || '',
                email: row.email || '',
            };
            this.judgeAddOrEdit = true;
            this.showpassword = true;
            this.display = {display: "flex"};
            this.disabled = false;
        },
        async handleDelete(tenantId) {
            console.log(tenantId);
            //删除
            request.delete(`/tenant/delete/${tenantId}`).then((res) => {
                if (res.code === 200) {
                    ElMessage({
                        message: "删除成功",
                        type: "success",
                    });
                    this.load();
                } else {
                    ElMessage({
                        message: res.msg,
                        type: "error",
                    });
                }
            });
        },
        handleSizeChange(pageSize) {
            this.pageSize = pageSize;
            this.tableData = this.paginatedData;
        },
        handleCurrentChange(pageNum) {
            this.currentPage = pageNum;
            this.tableData = this.paginatedData;
        },
    },
};